using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

namespace Rioshu.Web.ViewStateHandlers
{
    internal sealed class ZipCompressor : IStringCompressor
    {
        public string Compress(string input)
        {
            var memStream = new MemoryStream();
            using (var zipStream = new DeflaterOutputStream(memStream, new Deflater(Deflater.BEST_COMPRESSION))) {
                var buffer = Encoding.UTF8.GetBytes(input);
                zipStream.Write(buffer, 0, buffer.Length);
            }

            var zipBytes = memStream.ToArray();
            memStream.Close();

            return Convert.ToBase64String(zipBytes);
        }

        public string Decompress(string input)
        {
            var inStream = new MemoryStream(Convert.FromBase64String(input));
            var outStream = new MemoryStream();
            using (var zipStream = new InflaterInputStream(inStream, new Inflater())) {
                int read;
                var buffer = new byte[4096];
                while ((read = zipStream.Read(buffer, 0, buffer.Length)) != 0) {
                    outStream.Write(buffer, 0, read);
                }
            }

            var outBytes = outStream.ToArray();
            inStream.Close();
            outStream.Close();

            return Encoding.UTF8.GetString(outBytes);
        }
    }
}